import * as qiniu from 'qiniu-js'


/**
 * post 请求方法
 * @param url
 * @param data
 * @return {Promise}
 */
export function QiniuUpload(token, data) {
    console.log('七牛token===>', token);
    console.log('七牛data===>', data);
    console.log(data.file.name);
    let endName = String(data.file.name).split('.').pop()
    console.log('endName===>', endName);
    let timestamp = (new Date()).getTime();
    let putExtra = {
        fname: data.file.name,
        params: {},
        mimeType: null
    }
    let config = {
        useCdnDomain: false,
        region: null
    }
    return new Promise((resolve, reject) => {
        let num = 0;
        this.observable = qiniu.upload(data.file, `${timestamp}.${endName}`, token.uptoken, putExtra, config)
        this.subscription = this.observable.subscribe((res) => {
            // console.log('res.total.percent==>', res.total.percent)
            num = res.total.percent;
            // console.log('num', num);

        }, (err) => {
            // console.log(err)
            reject(err);
        }, (res) => {
            // console.log('res===>', res);
            // console.log('num===>', num);
            if (num == 100) {
                resolve(res);
            }
        })

    })
}


export function Base64ImgUpload(token, data, fn) {
    let timestamp = (new Date()).getTime();
    let pic = data
    let key = window.btoa(timestamp + '.png')
    pic = pic.replace(/^data:image\/(jpeg|png|gif);base64,/, '')
    let url = 'http://upload.qiniup.com/putb64/-1/key/' + key // 非华东空间需要根据注意事项 1 修改上传域名
    let xhr = new XMLHttpRequest()
    xhr.onreadystatechange = () => {
        if (xhr.readyState == 4) {
            return fn(JSON.parse(xhr.responseText));
        }
        //  else {
        //     console.log(1234);
        //     reject(xhr)
        // }
    }
    xhr.open('POST', url, false)
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    xhr.setRequestHeader('Authorization', 'UpToken ' + token.uptoken)
    xhr.send(pic)
    // return new Promise((resolve, reject) => {

    // })
    // reject(err);
    // resolve(res);
}